const { join } = require('path');
const { readFileSync, writeFileSync, existsSync, mkdirSync } = require('fs');
const { Parser } = require("htmlparser2");
const { DomHandler } = require("domhandler");
const domutils = require("domutils");
const render = require("dom-serializer").default;

const normalPxReg = /(\d+(\.\d+)?)px/g;
const rawHtml = readFileSync('src/index.html', "utf-8");

const options = {
  remUnit: 75,
  remPrecision: 5
}



const handler = new DomHandler((error, dom) => {
  if (error) {
    // Handle error
  } else {
    // Parsing completed, do something
    const withAttribsNodes = domutils.findAll((el => {
      return el.attribs.style;
    }), dom);
    if (withAttribsNodes.length) {
      withAttribsNodes.forEach(item => {
        item.attribs.style = calcValue(item.attribs.style);
      });
    }
    const result = render(dom);
    const dirPath = join(__dirname, 'dist');
    if (!existsSync(dirPath)) {
      mkdirSync(dirPath, { recursive: true });
    }
    writeFileSync(dirPath + '/index.html', result);
  }
});
const parser = new Parser(handler);
parser.write(rawHtml);
parser.end();


function calcValue(value) {
  const {remUnit, remPrecision} = options;
  return value.replace(normalPxReg, (_, $1) => {
    let val = (+$1 / remUnit).toFixed(remPrecision);
    return val + 'rem';
  });
}
